package com.youdianstar.app.util

import android.content.Context
import com.youdianstar.app.common.util.DateUtil
import com.youdianstar.app.common.util.MathUtil
import com.youdianstar.app.R
import com.youdianstar.app.entity.BillingPlan
import com.youdianstar.app.entity.CouponDeduct
import com.youdianstar.app.entity.OpenItem
import com.youdianstar.app.entity.OpenTime
import com.youdianstar.app.entity.OpenTimeJson
import com.youdianstar.app.entity.RentboxConfig
import com.youdianstar.app.util.DataAppManager
import zion830.com.range_picker_dialog.TimeRange
import java.util.Calendar
import java.util.GregorianCalendar


/**
 * File: DataHelperEx
 * Author: 82149 Create: 2022/3/30 12:26
 * Changes (from 2022/3/30)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
object DataHelperEx {
    /**获取默认区间列表*/
    fun getListDefault(): MutableList<OpenItem> {
        val list = mutableListOf<OpenItem>()
        list.add(
            OpenItem(
                1,
                allDay = true,
                check = true,
                mutableListOf("0:00", "0:00"),
                mutableListOf(), mutableListOf(), mutableListOf())
        )
        list.add(
            OpenItem(
                2,
                allDay = true,
                check = true,
                mutableListOf("0:00", "0:00"),
                mutableListOf(), mutableListOf(), mutableListOf())
        )
        list.add(
            OpenItem(
                3,
                allDay = true,
                check = true,
                mutableListOf("0:00", "0:00"),
                mutableListOf(), mutableListOf(), mutableListOf())
        )
        list.add(
            OpenItem(
                4,
                allDay = true,
                check = true,
                mutableListOf("0:00", "0:00"),
                mutableListOf(), mutableListOf(), mutableListOf())
        )
        list.add(
            OpenItem(
                5,
                allDay = true,
                check = true,
                mutableListOf("0:00", "0:00"),
                mutableListOf(), mutableListOf(), mutableListOf())
        )
        list.add(
            OpenItem(
                6,
                allDay = true,
                check = true,
                mutableListOf("0:00", "0:00"),
                mutableListOf(), mutableListOf(), mutableListOf())
        )
        list.add(
            OpenItem(
                0,
                allDay = true,
                check = true,
                mutableListOf("0:00", "0:00"),
                mutableListOf(), mutableListOf(), mutableListOf())
        )
        return list
    }

    /**获取区间列表*/
    fun getOpentimeList(json: OpenTimeJson): MutableList<OpenItem> {
        val list = mutableListOf<OpenItem>()
        try {
            json.businessHours.forEach {
                list.add(it.copyOpenItem())
            }
        } catch (e: Exception) {
            list.addAll(getListDefault())
        }
        return list
    }

    fun copyOpentimeList(dataList: MutableList<OpenItem>): MutableList<OpenTime> {
        val copyList = mutableListOf<OpenTime>()
        dataList.forEach {
            copyList.add(
                OpenTime(
                    it.value,
                    allDay = it.allDay,
                    check = it.check,
                    rangeTime1 = it.rangeTime1,
                    rangeTime2 = it.rangeTime2,
                    rangeTime3 = it.rangeTime3,
                    rangeTime4 = it.rangeTime4
                )
            )
        }
        return copyList
    }

    /**
     * 将 [xx:xx,xx:xx]转换成TimeRange
     *
     * @return TimeRange obj
     */
    fun getRangeByStr(data: List<String>?): TimeRange {
        if (data.isNullOrEmpty()) {
            return TimeRange(0, 0, 0, 0)
        }
        var startHour = 0
        var startMin = 0
        var endHour = 0
        var endMin = 0
        try {
            val timeStart = data[0]
            val timeEnd = data[1]
            val spl = timeStart.split(":").toTypedArray()
            val epl = timeEnd.split(":").toTypedArray()
            startHour = spl[0].toInt()
            startMin = spl[1].toInt()
            endHour = epl[0].toInt()
            endMin = epl[1].toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return TimeRange(startHour, startMin, endHour, endMin)
    }

    /**
     * 将 TimeRange 转换成 [xx:xx,xx:xx]
     *
     * @return TimeRange obj
     */
    fun getRangeList(range: TimeRange): MutableList<String> {
        val data: MutableList<String> = ArrayList()
        data.add(range.getStartTimeSequence())
        data.add(range.getEndTimeSequence())
        return data
    }

    /**充电卡 免费时长*/
    fun chargingFreeTx(mContext: Context, duration: Long): String {
        if (duration == 0L)
            return "0 " + mContext.getString(R.string.coupon_min)
        val hour: Long = duration / (60 * 60)
        return if (hour > 0) {
            hour.toString() + " " + mContext.getString(R.string.coupon_hour)
        } else {
            val min: Long = duration / 60
            min.toString() + " " + mContext.getString(R.string.coupon_min)
        }
    }

    /**计费规则文本*/
    fun pricePlanTx(mContext: Context, bill: BillingPlan): String {
        var planTx = ""
        if (bill.isSystem) {
            planTx = mContext.getString(R.string.time_freeUsage)
        } else {
            val symbolStr = DataAppManager.instance.symbolTx().uppercase()
            //0-不限制(每单)/1-每天首单/2-每天前两单/3-每天前三单/4-每天前四单/5-每天前五单
            val freeTx: String = when (bill.freeLimit) {
                1 -> {
                    String.format(mContext.getString(R.string.time_dayOrder1),
                        typeValueTx(mContext, bill.freeDuration, bill.freeDurationControlType)
                    )
                }

                2 -> {
                    String.format(mContext.getString(R.string.time_dayOrder2),
                        typeValueTx(mContext, bill.freeDuration, bill.freeDurationControlType)
                    )
                }

                3 -> {
                    String.format(mContext.getString(R.string.time_dayOrder3),
                        typeValueTx(mContext, bill.freeDuration, bill.freeDurationControlType)
                    )
                }

                4 -> {
                    String.format(mContext.getString(R.string.time_dayOrder4),
                        typeValueTx(mContext, bill.freeDuration, bill.freeDurationControlType)
                    )
                }

                5 -> {
                    String.format(mContext.getString(R.string.time_dayOrder5),
                        typeValueTx(mContext, bill.freeDuration, bill.freeDurationControlType)
                    )
                }

                else -> {
                    String.format(mContext.getString(R.string.time_dayOrder0),
                        typeValueTx(mContext, bill.freeDuration, bill.freeDurationControlType)
                    )
                }
            }
            //每分钟/小时/天 计费
            val perCostTx = String.format(mContext.getString(R.string.rule_perTime),
                symbolStr + MathUtil.round(bill.amount),
                typeValueTx(mContext, bill.cycle, bill.controlType)
            )
            val perCostAfterTx = String.format(mContext.getString(R.string.rule_perTimeAfter),
                symbolStr + MathUtil.round(bill.amount),
                typeValueTx(mContext, bill.cycle, bill.controlType)
            )

            //每日封顶
            val dailyCapTx = String.format(mContext.getString(R.string.rule_dailyCap),
                symbolStr + MathUtil.round(bill.dayAmount)
            )
            //总封顶+最大时长
            val maxCostTx = String.format(mContext.getString(R.string.rule_totalCap),
                symbolStr + MathUtil.round(bill.penaltyAmount),
                typeValueTx(mContext, bill.maxRentDuration, bill.maxDurationControlType)
            )


            if (bill.freeDuration > 0 && bill.dayAmount > 0) {
                //非必填项都不为空 (免单+计费+每日封顶+总封顶与最大时长)
                planTx = "$freeTx $perCostAfterTx$dailyCapTx$maxCostTx"
            } else if (bill.freeDuration == 0 && bill.dayAmount > 0) {
                //免费使用为空,每日封顶费用>0
                planTx = perCostTx + dailyCapTx + maxCostTx
            } else if (bill.freeDuration > 0 && bill.dayAmount == 0F) {
                //免费不为空,每日封顶费用==0
                planTx = "$freeTx $perCostAfterTx$maxCostTx"
            } else {
                //只显示 计费+最大时长
                planTx = perCostTx + maxCostTx
            }
        }
        return planTx
    }

    private fun typeValueTx(mContext: Context, value: Int, type: Int): String {
        //1-分 2-小时 3-天
        var typeTx = ""
        when (type) {
            3 -> {
                typeTx = value.toString() + " " + mContext.getString(if (value > 1) R.string.time_days else R.string.time_day)
            }

            2 -> {
                typeTx = value.toString() + " " + mContext.getString(if (value > 1) R.string.time_hours else R.string.time_hour)
            }

            1 -> {
                typeTx = value.toString() + " " + mContext.getString(if (value > 1) R.string.time_mins else R.string.time_min)
            }
        }
        return typeTx
    }


    /**
     * 获取优惠券规则
     * @param mContext 上下文
     */
    fun couponDeductTx(mContext: Context, symbolTx: String, bean: CouponDeduct) :String{
        var deductName = "--"
        var deductTx = ""
        when (bean.type) {
            1 -> {
                deductName = mContext.getString(R.string.coupon_freeUsage)
                //1-分钟 2-小时
                deductTx = when (bean.type1FreeDurationUnit) {
                    1 -> {
                        (if (bean.type1FreeDurationVal > 0) bean.type1FreeDurationVal.toString() else "0") +
                                " " + mContext.getString(R.string.coupon_min)
                    }

                    2 -> {
                        (if (bean.type1FreeDurationVal > 0) bean.type1FreeDurationVal.toString() else "0") +
                                " " + mContext.getString(R.string.coupon_hour)
                    }

                    else -> {
                        (if (bean.type1FreeDurationVal > 0) bean.type1FreeDurationVal.toString() else "0") +
                                " " + mContext.getString(R.string.coupon_day)
                    }
                }
            }

            2 -> {
                deductName = mContext.getString(R.string.coupon_freeRental)
                deductTx = symbolTx + MathUtil.round(bean.type2DiscountAmount ?: 0.0)
            }

            3 -> {
                deductName = mContext.getString(R.string.coupon_rentalDiscount)
                deductTx = String.format(mContext.getString(R.string.coupon_off), bean.type3DiscountNum() + "%")
            }
        }
        return "$deductName $deductTx"
    }


    /**
     * 根据偏移天数,计算结束时间
     * @param offset 偏移天数 正值
     */
    fun checkCouponEndDate(offset: Int): String {
        val endDate = GregorianCalendar.getInstance()
        endDate.timeInMillis = System.currentTimeMillis()
        endDate.add(Calendar.DAY_OF_YEAR, offset)
//        endDate.set(Calendar.HOUR_OF_DAY, 23)
//        endDate.set(Calendar.MINUTE, 59)
//        endDate.set(Calendar.SECOND, 59)
//        endDate.set(Calendar.MILLISECOND, 0)
        return DateUtil.getOrderTime(endDate.timeInMillis)
    }

    /**
     * 充电卡显示时长, 优惠券/优惠码 特殊处理
     * @param mContext 上下文
     */
    fun couponDeductTime(mContext: Context,symbolTx: String, bean: CouponDeduct,amount:Double):String{
        if (bean.type == 1){
            val deductName = mContext.getString(R.string.coupon_freeUsage)
            val deductTx = when (bean.type1FreeDurationUnit) {
                1 -> {
                    (if (bean.type1FreeDurationVal > 0) bean.type1FreeDurationVal.toString() else "0") + " " + mContext.getString(R.string.coupon_min)
                }

                2 -> {
                    (if (bean.type1FreeDurationVal > 0) bean.type1FreeDurationVal.toString() else "0") + " " + mContext.getString(R.string.coupon_hour)
                }

                else -> {
                    (if (bean.type1FreeDurationVal > 0) bean.type1FreeDurationVal.toString() else "0") + " " + mContext.getString(R.string.coupon_day)
                }
            }
            return "$deductName $deductTx"
        }else{
            return "$symbolTx ${MathUtil.round(amount)}"
        }
    }

    /**机柜计费规则文本格式化 - 参考iOS实现，使用formatVietnameseDong格式化金额*/
    fun rentboxConfigPlanTx(mContext: Context, config: RentboxConfig): String {
        val sb = StringBuilder()
        val currencyUnit = "đ" // 越南盾单位
        
        // 免费分钟数（参考iOS：minuteFree > 0 ? minuteFree : 5）
        val minuteFree = if (config.minuteFree > 0) config.minuteFree else 5
        val freeText = mContext.getString(R.string.scan_free_minutes, minuteFree)
        sb.append(freeText).append("\n")
        
        // 首分钟费用（参考iOS：直接使用fistMinuteFee，使用formatVietnameseDong格式化，并添加单位）
        val firstMinuteFee = config.fistMinuteFee
        val firstMinuteFeeText = "${MathUtil.formatVietnameseDong(firstMinuteFee)}$currencyUnit"
        val firstMinuteText = mContext.getString(R.string.scan_first_minute, firstMinuteFeeText, 1)
        sb.append(firstMinuteText).append("\n")
        
        // 周期费用（参考iOS：直接使用cycleFee，使用formatVietnameseDong格式化，并添加单位）
        // 格式：金额đ/周期时间（如：0.11đ/60分钟）
        val cycleFee = config.cycleFee
        val cycleFeeText = "${MathUtil.formatVietnameseDong(cycleFee)}$currencyUnit"
        val minuteCycle = if (config.minuteCycle > 0) config.minuteCycle else 30
        // 周期时间显示为分钟数（如：60分钟），而不是"1小时"
        val cycleMinutes = "${minuteCycle}${mContext.getString(R.string.scan_minute_unit)}"
        val cycleText = mContext.getString(R.string.scan_cycle_fee, cycleFeeText, cycleMinutes, "")
        sb.append(cycleText).append("\n")
        
        // 每日费用（参考iOS：直接使用dayFee，使用formatVietnameseDong格式化，并添加单位）
        val dayFee = config.dayFee
        val dayFeeText = "${MathUtil.formatVietnameseDong(dayFee)}$currencyUnit"
        val dayText = mContext.getString(R.string.scan_day_cap, dayFeeText)
        sb.append(dayText).append("\n")
        
        // 押金（参考iOS：直接使用securityFee，使用formatVietnameseDong格式化，并添加单位）
        val securityFee = config.securityFee
        val securityFeeText = "${MathUtil.formatVietnameseDong(securityFee)}$currencyUnit"
        val securityText = mContext.getString(R.string.scan_security_fee, securityFeeText)
        sb.append(securityText)
        
        return sb.toString()
    }
}